<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="门店ID" prop="storeInfoId">
        <el-select
            v-model="queryParams.storeInfoId"
            placeholder="请选择门店ID"
            clearable
            filterable
            remote
            :remote-method="remoteSearchStoreInfo"
            :loading="storeInfoLoading"
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in storeInfoOptions"
              :key="item.id"
              :label="`${item.id}${item.storeName ? `（${item.storeName}）` : ''}`"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 修改订单ID为下拉搜索框 -->
      <el-form-item label="订单ID" prop="shopOrderId">
        <el-select
            v-model="queryParams.shopOrderId"
            placeholder="请选择订单ID"
            clearable
            filterable
            remote
            :remote-method="remoteSearchShopOrder"
            :loading="shopOrderLoading"
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in shopOrderOptions"
              :key="item.id"
              :label="item.id"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 修改商品SPU ID为下拉搜索框 -->
      <el-form-item label="商品SPU ID" prop="spuId">
        <el-select
            v-model="queryParams.spuId"
            placeholder="请选择商品SPU ID"
            clearable
            filterable
            remote
            :remote-method="remoteSearchSpu"
            :loading="spuLoading"
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in spuOptions"
              :key="item.id"
              :label="`${item.id}${item.name ? `（${item.name}）` : ''}`"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 修改用户ID为下拉搜索框 -->
      <el-form-item label="用户ID" prop="membersId">
        <el-select
            v-model="queryParams.membersId"
            placeholder="请选择用户ID"
            clearable
            filterable
            remote
            :remote-method="remoteSearchMembers"
            :loading="membersLoading"
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in membersOptions"
              :key="item.id"
              :label="`${item.id}${item.nickname ? `（${item.nickname}）` : ''}`"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="用户名" prop="username">
        <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评分，1~5星" prop="rating">
        <el-select v-model="queryParams.rating" placeholder="请选择评分" clearable style="width:200px">
          <el-option
              v-for="dict in product_comments_rating"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['transaction:YZMcomments:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['transaction:YZMcomments:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['transaction:YZMcomments:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['transaction:YZMcomments:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="YZMcommentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评论ID" align="center" prop="id" />
      <el-table-column label="门店ID" align="center" prop="storeInfoId">
        <template #default="scope">
    <span v-if="scope.row.storeInfo">
      {{ scope.row.storeInfo.id }}（{{ scope.row.storeInfo.name }}）
    </span>
          <span v-else>
      {{ scope.row.storeInfoId }}
    </span>
        </template>
      </el-table-column>

      <el-table-column label="订单ID" align="center" prop="shopOrderId">
        <template #default="scope">
    <span v-if="scope.row.shopOrder">
      {{ scope.row.shopOrder.id }}（{{ scope.row.shopOrder.orderNo }}）
    </span>
          <span v-else>
      {{ scope.row.shopOrderId }}
    </span>
        </template>
      </el-table-column>

      <el-table-column label="商品SPU ID" align="center" prop="spuId">
        <template #default="scope">
    <span v-if="scope.row.spu">
      {{ scope.row.spu.id }}（{{ scope.row.spu.name }}）
    </span>
          <span v-else>
      {{ scope.row.spuId }}
    </span>
        </template>
      </el-table-column>

      <el-table-column label="用户ID" align="center" prop="membersId">
        <template #default="scope">
    <span v-if="scope.row.members">
      {{ scope.row.members.id }}（{{ scope.row.members.nickname }}）
    </span>
          <span v-else>
      {{ scope.row.membersId }}
    </span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="评分，1~5星" align="center" prop="rating">
        <!--      <el-table-column label="商品SKU ID" align="center" prop="skuId" />-->
        <template #default="scope">
          <dict-tag :options="product_comments_rating" :value="scope.row.rating"/>
        </template>
      </el-table-column>
      <el-table-column label="评论内容" align="center" prop="content" />
      <el-table-column label="评论图片" align="center" prop="images" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="是否匿名评价：0-否，1-是" align="center" prop="isAnonymous">
        <template #default="scope">
          <dict-tag :options="product_comments_anoymous" :value="scope.row.isAnonymous"/>
        </template>
      </el-table-column>
      <el-table-column label="是否展示" prop="isShow">
        <template #default="{ row }">
          {{ row.isShow === 1 ? '展示' : '隐藏' }}
        </template>
      </el-table-column>
      <el-table-column label="回复数量" align="center" prop="replyCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['transaction:YZMcomments:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['transaction:YZMcomments:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商品评价对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="YZMcommentsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="门店ID" prop="storeInfoId">
          <el-select
              v-model="form.storeInfoId"
              placeholder="请选择门店ID"
              filterable
              remote
              :remote-method="remoteSearchStoreInfo"
              :loading="storeInfoLoading"
          >
            <el-option
                v-for="item in storeInfoOptions"
                :key="item.id"
                :label="`${item.id}${item.storeName ? `（${item.storeName}）` : ''}`"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 修改订单ID为下拉搜索框 -->
        <el-form-item label="订单ID" prop="shopOrderId">
          <el-select
              v-model="form.shopOrderId"
              placeholder="请选择订单ID"
              filterable
              remote
              :remote-method="remoteSearchShopOrder"
              :loading="shopOrderLoading"
          >
            <el-option
                v-for="item in shopOrderOptions"
                :key="item.id"
                :label="item.id"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 修改商品SPU ID为下拉搜索框 -->
        <el-form-item label="商品SPU ID" prop="spuId">
          <el-select
              v-model="form.spuId"
              placeholder="请选择商品SPU ID"
              filterable
              remote
              :remote-method="remoteSearchSpu"
              :loading="spuLoading"
          >
            <el-option
                v-for="item in spuOptions"
                :key="item.id"
                :label="`${item.id}${item.name ? `（${item.name}）` : ''}`"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 修改用户ID为下拉搜索框 -->
        <el-form-item label="用户ID" prop="membersId">
          <el-select
              v-model="form.membersId"
              placeholder="请选择用户ID"
              filterable
              remote
              :remote-method="remoteSearchMembers"
              :loading="membersLoading"
          >
            <el-option
                v-for="item in membersOptions"
                :key="item.id"
                :label="`${item.id}${item.nickname ? `（${item.nickname}）` : ''}`"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="评分，1~5星" prop="rating">
          <el-select v-model="form.rating" placeholder="请选择评分，1~5星" >
            <el-option
                v-for="dict in product_comments_rating"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评论内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="评论图片" prop="images">
          <image-upload v-model="form.images"/>
        </el-form-item>
        <el-form-item label="是否匿名评价" prop="isAnonymous">
          <el-radio-group v-model="form.isAnonymous">
            <el-radio
                v-for="dict in product_comments_anoymous"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否展示" prop="isShow">
          <el-radio-group v-model="form.isShow">
            <el-radio :label="1">展示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回复数量" prop="replyCount">
          <el-input v-model="form.replyCount" placeholder="请输入回复数量" />
        </el-form-item>
        <el-form-item label="逻辑删除" prop="delFlag">
          <el-radio-group v-model="form.delFlag">
            <el-radio
                v-for="dict in del_flag"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="YZMcomments">
import { listYZMcomments, getYZMcomments, delYZMcomments, addYZMcomments, updateYZMcomments } from "@/api/transaction/YZMcomments"
import { listStoreInfo } from "@/api/core/storeInfo"
import { listShoporder } from "@/api/transaction/shoporder"
import { listSpuVo } from "@/api/transaction/spu"
import { listMembers } from "@/api/core/members"
import { onMounted } from 'vue'
const { proxy } = getCurrentInstance()
const { product_comments_rating, product_comments_anoymous, product_comments_show, del_flag } = proxy.useDict('product_comments_rating', 'product_comments_anoymous', 'product_comments_show', 'del_flag')

const YZMcommentsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 新增的状态变量
const storeInfoOptions = ref([])
const shopOrderOptions = ref([])
const spuOptions = ref([])
const membersOptions = ref([])
const storeInfoLoading = ref(false)
const shopOrderLoading = ref(false)
const spuLoading = ref(false)
const membersLoading = ref(false)


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeInfoId: null,
    shopOrderId: null,
    spuId: null,
    skuId: null,
    membersId: null,
    username: null,
    rating: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

// 远程搜索门店方法
const remoteSearchStoreInfo = async (query) => {
  storeInfoLoading.value = true
  try {
    const response = await listStoreInfo({
      pageNum: 1,
      pageSize: 100,
      ...(query ? { storeName: query } : {})
    })
    storeInfoOptions.value = response.rows || []
  } catch (error) {
    console.error("搜索门店失败:", error)
    storeInfoOptions.value = []
  } finally {
    storeInfoLoading.value = false
  }
}

// 远程搜索订单方法
const remoteSearchShopOrder = async (query) => {
  shopOrderLoading.value = true
  try {
    const response = await listShoporder({
      pageNum: 1,
      pageSize: 100,
      ...(query ? { orderNo: query } : {})
    })
    shopOrderOptions.value = response.rows || []
  } catch (error) {
    console.error("搜索订单失败:", error)
    shopOrderOptions.value = []
  } finally {
    shopOrderLoading.value = false
  }
}

// 远程搜索商品SPU方法
const remoteSearchSpu = async (query) => {
  spuLoading.value = true
  try {
    const response = await listSpuVo({
      pageNum: 1,
      pageSize: 100,
      ...(query ? { name: query } : {})
    })
    spuOptions.value = response.rows || []
  } catch (error) {
    console.error("搜索商品SPU失败:", error)
    spuOptions.value = []
  } finally {
    spuLoading.value = false
  }
}

// 远程搜索用户方法
const remoteSearchMembers = async (query) => {
  membersLoading.value = true
  try {
    const response = await listMembers({
      pageNum: 1,
      pageSize: 100,
      ...(query ? { nickName: query } : {})
    })
    membersOptions.value = response.rows || []
  } catch (error) {
    console.error("搜索用户失败:", error)
    membersOptions.value = []
  } finally {
    membersLoading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  remoteSearchStoreInfo('')
  remoteSearchShopOrder('')
  remoteSearchSpu('')
  remoteSearchMembers('')
})




/** 查询商品评价列表 */
function getList() {
  loading.value = true
  listYZMcomments(queryParams.value).then(response => {
    YZMcommentsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    storeInfoId: null,
    shopOrderId: null,
    spuId: null,
    skuId: null,
    membersId: null,
    username: null,
    rating: null,
    content: null,
    images: null,
    isAnonymous: null,
    isShow: 1 ,
    replyCount: null,
    delFlag: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("YZMcommentsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 修改新增按钮操作
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品评价"
  // 确保有最新的选项数据
  if (storeInfoOptions.value.length === 0) {
    remoteSearchStoreInfo('')
  }
  if (shopOrderOptions.value.length === 0) {
    remoteSearchShopOrder('')
  }
  if (spuOptions.value.length === 0) {
    remoteSearchSpu('')
  }
  if (membersOptions.value.length === 0) {
    remoteSearchMembers('')
  }
}

// 修改修改按钮操作
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getYZMcomments(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商品评价"
    // 确保有最新的选项数据
    if (storeInfoOptions.value.length === 0) {
      remoteSearchStoreInfo('')
    }
    if (shopOrderOptions.value.length === 0) {
      remoteSearchShopOrder('')
    }
    if (spuOptions.value.length === 0) {
      remoteSearchSpu('')
    }
    if (membersOptions.value.length === 0) {
      remoteSearchMembers('')
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["YZMcommentsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateYZMcomments(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addYZMcomments(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商品评价编号为"' + _ids + '"的数据项？').then(function() {
    return delYZMcomments(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('transaction/YZMcomments/export', {
    ...queryParams.value
  }, `YZMcomments_${new Date().getTime()}.xlsx`)
}

getList()
</script>
